﻿using System;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using Microsoft.Extensions.Options;
using System.Threading.Tasks;
using WxLib.Core.Util;
using WxLib.Core.RequestHandlers;
using WxLib.Core.Serializers;

namespace WxLib.Sns
{
    public class WxSns : WxLibApiBase
    {
        private readonly TraceSource _trace = new TraceSource("WxLib", SourceLevels.All);
        private const string DefaultHost = "https://api.weixin.qq.com";
        private const string DefaultApiPath = "/";
        private readonly WxApiOptions options;

        /// <summary>
        /// 构造函数
        /// </summary>
        public WxSns(IOptions<WxApiOptions> optionsAccessor)
            : base(DefaultHost, new RequestHandler(new JsonSerializer()))
        {
            this.ApiPath = DefaultApiPath;
            this.options = optionsAccessor.Value;
        }

        /// <summary>
        /// code 换取 session_key
        /// </summary>
        /// <param name="loginCode"></param>
        /// <returns></returns>
        public Task<Code2SessionResponse> GetJsCode2SessionAsync(string loginCode)
        {
            Contract.Requires(loginCode != null, "logincode cannot be null.");
            string relPath = "sns/jscode2session?appid=" + options.AppId + "&secret=" + options.AppSecret + "&js_code=" + loginCode + "&grant_type=authorization_code";
            return requestAsync<Code2SessionResponse>(relPath);
        }

        /// <summary>
        /// code 换取 session_key
        /// </summary>
        /// <param name="loginCode"></param>
        /// <returns></returns>
        public Code2SessionResponse GetJsCode2Session(string loginCode)
        {
            return GetJsCode2SessionAsync(loginCode).Result;
        }


        /// <summary>
        /// 根据appId appsecret 获取用户信息
        /// </summary>
        /// <param name="loginCode"></param>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public Task<Code2SessionResponse> GetJsCode2SessionAsync(string loginCode,string appId,string appSecret)
        {
            Contract.Requires(loginCode != null, "logincode cannot be null.");
            string relPath = "sns/jscode2session?appid=" + appId + "&secret=" + appSecret + "&js_code=" + loginCode + "&grant_type=authorization_code";
            return requestAsync<Code2SessionResponse>(relPath);
        }

    }
}
